﻿using DoNet.Common.Helpers;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

namespace DoNet.Extensions.ServiceExtensions
{
    /// <summary>
    /// 跨域服务
    /// </summary>
    public static class CorsSetup
    {
        /// <summary>
        /// 跨域启动服务
        /// </summary>
        /// <param name="services"></param>
        /// <param name="config"></param>
        /// <exception cref="ArgumentNullException"></exception>
        public static void AddCorsSetup(this IServiceCollection services, IConfiguration config)
        {
            if (services != null)
            {
                //跨域设置 注意：只要设置有 * 就是允许所有跨域访问。
                string allowOrigins = config.app("AllowedHosts");
                if (!string.IsNullOrWhiteSpace(allowOrigins))
                {
                    var newOriginsArray = new string[] { "*" }; //允许所有跨域访问
                    var allowOriginsArray = allowOrigins.Split(',', StringSplitOptions.RemoveEmptyEntries);
                    if (allowOriginsArray.Length > 0)
                    {
                        var isAllAllow = allowOriginsArray.ToList().Contains("*");
                        if (!isAllAllow)
                        {
                            newOriginsArray = allowOriginsArray;
                        }
                        services.AddCors(options => options.AddPolicy("Cors", policy => policy.WithOrigins(newOriginsArray).AllowAnyHeader().AllowAnyMethod()));
                    }
                }
            }
            else
                throw new ArgumentNullException(nameof(services));
        }

        /// <summary>
        /// 跨域中间件
        /// </summary>
        /// <param name="builder"></param>
        /// <returns></returns>
        public static IApplicationBuilder UseCorsMiddleware(this IApplicationBuilder builder)
        {
            return builder.UseMiddleware<CorsMiddleware>();
        }
    }

    /// <summary>
    /// 跨域中间件
    /// 解决net core 3.1 跨域 Cors 找不到 “Access-Control-Allow-Origin”
    /// </summary>
    public class CorsMiddleware
    {
        /// <summary>
        /// 
        /// </summary>
        private readonly RequestDelegate _next;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="next"></param>
        public CorsMiddleware(RequestDelegate next)
        {
            _next = next;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="httpContext"></param>
        /// <returns></returns>
        public async Task Invoke(HttpContext httpContext)
        {
            if (!httpContext.Response.Headers.ContainsKey("Access-Control-Allow-Origin"))
            {
                httpContext.Response.Headers.Append("Access-Control-Allow-Origin", "*");
            }
            await _next(httpContext);
        }
    }
}
